/*=======================================
Looping over individuals to do FWL regressions 
=========================================*/


include "config.do" 

#delimit ; 

use $datadir/cte_regressions.dta, clear ;

/********************************************
Need to regress a number of variables on trend:

logearn
enrolled
grad_dummy
age dummies

**********************************************/
tab age, gen(age_) ;
tab qtime, gen(qtr_) ; 
egen group = group(pik) ;
sum group ; 
local max = r(max) ;

/******************************
Doing the de-trending
******************************/

summ earn_* logearn_* ;

foreach samplevar of varlist earn_national earn_state { ;
preserve ; 
gen insample_earn = (`samplevar' > 0 & `samplevar' != . ) ;
                                                        
foreach earnvar of varlist `samplevar' log`samplevar'  enrolled grad_dummy age_* qtr_* { ;
      egen temp=sd(qtime) if insample_earn==1 , by(pik) ;
      gen vart_hs = temp^2 ;
      drop temp ;

      egen tbar=mean(qtime) if insample_earn==1, by(pik) ;
      egen wbar= mean(`earnvar') if insample_earn==1,by(pik) ;
      gen temp=(`earnvar' - wbar)*(qtime-tbar) if insample_earn==1;
      egen temp2=sum(temp) if insample_earn==1,by(pik);
      egen wageobs=count(`earnvar') if insample_earn==1, by(pik) ;

      gen covar=temp2/(wageobs-1) if insample_earn==1;
      drop temp temp2 ;
      gen beta_`earnvar' = covar/vart_hs if insample_earn==1;
      gen alpha_`earnvar' = wbar-beta_`earnvar'*tbar if insample_earn==1;
      gen wagehat_`earnvar'=alpha_`earnvar'+beta_`earnvar'*qtime if insample_earn==1 ;
      drop tbar wbar wageobs covar vart_hs;

      gen resid_`earnvar' = `earnvar' - wagehat_`earnvar' ;

      drop wagehat_`earnvar' ;
} ;

drop alpha_* beta_* age_* qtr_* ;

compress ;

save $datadir/cte_resid_`samplevar'.dta, replace  ;

restore ;
} ;
des ; 




